import axios from 'axios'
import Vue from 'vue'
import Config from '../settings'
import store from '../store/index'
import router from '../router/index'
// import { Message } from 'element-ui'
import { getToken, removeToken } from '../utils/token'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: Config.timeout,
  withCredentials: true
})

// 请求拦截器
request.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.token = getToken()
    config.headers.range = 'bytes=0--1'
  }
  return config
}, (error) => {
  // console.log(error)
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(res => {
  const code = Number(res.data.code)
  // console.log(res)
  switch (code) {
    case 704: case 707: {
      const redirect = router.currentRoute.name
      if (redirect !== 'login') {
        router.push(`/login?redirect=${redirect}`)
      } else {
        router.push('/login')
      }
      removeToken()
      break
    }
  }
  return res
})
Vue.prototype.$request = function (type, url, params) {
  return request[type](url, { params })
}
export default request
